// Copyright (c) 2020 Wang Zemin Personal. All Right Reserved

import * as React from "react";
import {Button, Card, Col, DatePicker, Form, Input, notification, Row, Select, Table} from "antd";
import {
    DeleteOutlined,
    FormOutlined,
    MessageOutlined,
    ReloadOutlined,
    SearchOutlined,
    SecurityScanOutlined,
    UserAddOutlined,
    UserOutlined
} from "@ant-design/icons";
import {Option} from "antd/es/mentions";
import CreateVerifyKeyModal from "../modals/CreateVerifyKeyModal";
import {disableKey, disableOwnKey, fetchAllKey, fetchAllOwnKey} from "../../requests/KeyManageRequest";
import UpdateVerifyKeyModal from "../modals/UpdateVerifyKeyModal";
import DisableVerifyKeyModal from "../modals/DisableVerifyKeyModal";

// import CreateVerifyKeyModal from "./CreateVerifyKeyModal";

class VerifyKeyManagePage extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            keys: [],
            selectedRowKey: "",
            pagination: {current: 1, pageSize: 10},
            searchFromRef: React.createRef(),
            isOwn: false,
            filters: {}
        };
    }

    componentDidMount = () => {
        this.refreshKeyData()
    }

    clickDisableKey = (e, keyName) => {
        if (this.props.isOwn) {
            console.log("Disable own key with name:" + JSON.stringify(keyName))
            disableOwnKey(keyName).then((edpKey) => {
                this.refreshKeyData()
                notification.info({message: "禁用激活码成功", description: "禁用激活码" + edpKey.result.keyName + "成功"});
            })
        } else {
            console.log("Disable all key with name:" + JSON.stringify(keyName))
            disableKey(keyName).then((edpKey) => {
                this.refreshKeyData()
                notification.info({message: "禁用激活码成功", description: "禁用激活码" + edpKey.result.keyName + "成功"});
            })
        }

    }

    onTableChange = (pagination) => {
        this.setState({pagination: pagination}, ()=>this.refreshKeyData(this.state.filters));
    }

    refreshKeyData = (filters = {}) => {
        if (this.props.isOwn) {
            console.log("List all own key ")
            fetchAllOwnKey(this.state.pagination, filters)
                .then((keyDomains) => {
                    let fetchKeys = keyDomains.result.map((userDomain) => this.toTableElement(userDomain))
                    this.setState({
                        keys: fetchKeys, pagination: {
                            current: keyDomains.pageNo,
                            pageSize: keyDomains.pageSize,
                            total: keyDomains.total
                        }
                    })
                })
        } else {
            console.log("List all all key ")
            fetchAllKey(this.state.pagination, filters)
                .then((keyDomains) => {
                    let fetchKeys = keyDomains.result.map((userDomain) => this.toTableElement(userDomain))
                    this.setState({
                        keys: fetchKeys, pagination: {
                            current: keyDomains.pageNo,
                            pageSize: keyDomains.pageSize,
                            total: keyDomains.total
                        }
                    })
                })
        }
    }

    searchKeys = (filters) => {
        console.log("Begin to refresh data with filter:" + JSON.stringify(filters))
        this.setState({
            filters: filters,
            pagination: {current: 1, pageSize: 10}
        },()=>this.refreshKeyData(filters))
    }

    resetSearchKeys = () => {
        this.state.searchFromRef.current.resetFields();
    };


    toTableElement = (keyDomain) => {
        return {
            "keyName": keyDomain.keyName,
            "createTime": keyDomain.createTime,
            "createBy": keyDomain.createBy,
            "deviceInfo": keyDomain.deviceInfo,
            "effectiveTime": keyDomain.effectiveTime,
            "expireTime": keyDomain.expireTime,
            "remainTimes": keyDomain.remainTimes,
            "status": keyDomain.status,
            "remark": keyDomain.remark,
            "username": keyDomain.username,
            "uuid": keyDomain.uuid,
        }
    }

    createKey = () => {
        this.state.createVerifyKeyModal.showModal()
    }

    updateKey = () => {
        this.state.updateVerifyKeyModal.showModal()
    }

    disableKey = () => {
        this.state.disableVerifyKeyModal.showModal()
    }

    render = () => {
        let pagination = this.state.pagination
        const keyColumns = [
            {
                title: '激活码唯一名称',
                dataIndex: 'keyName',
                key: 'keyName',
            },
            {
                title: '创建时间',
                dataIndex: 'createTime',
                key: 'createTime',
            },
            {
                title: '创建人',
                dataIndex: 'createBy',
                key: 'createBy',
            },
            {
                title: '绑定的设备',
                dataIndex: 'deviceInfo',
                key: 'deviceInfo',
            },
            {
                title: '第一次使用时间',
                dataIndex: 'effectiveTime',
                key: 'effectiveTime',
            }, {
                title: '过期时间',
                dataIndex: 'expireTime',
                key: 'expireTime',
            },
            {
                title: '可用次数',
                dataIndex: 'remainTimes',
                key: 'remainTimes',
            },
            {
                title: '状态',
                dataIndex: 'status',
                key: 'status',
                render: (text, record, index) => (
                    <Button type="dashed" danger disabled={record.status !== "NORMAL"} key={record.keyName}>{record.status}</Button>
                ),
            },
            {
                title: '发放对象',
                dataIndex: 'username',
                key: 'username',
            },
            {
                title: '备注',
                dataIndex: 'remark',
                key: 'remark',
            }]

        const rowSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                console.log(`Current selected keys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
                this.setState({
                    selectedRowKey: selectedRows[0].keyName
                })
            }
        };


        return (
            <div style={{padding: 10, margin: 10}}>
                <Card title="激活码搜索条件">
                    <Form name="basic" ref={this.state.searchFromRef} layout="inline" onFinish={this.searchKeys}
                          style={{marginTop: 10, marginBottom: 10, width: '100%', border: "1", borderColor: "#000000"}}>

                        <Row style={{width: '100%'}}>

                            <Col span={8} offset={1}>
                                <Form.Item name="keyName">
                                    <Input prefix={<SecurityScanOutlined/>} placeholder="激活码唯一标识"
                                           style={{width: '98%'}}/>
                                </Form.Item>
                            </Col>
                            <Col span={3} offset={1}>
                                <Form.Item name="createBy" style={{width: '95%'}}>
                                    <Input prefix={<UserOutlined/>} placeholder="激活码创建者"/>
                                </Form.Item>
                            </Col>
                            <Col span={6} offset={1}>
                                <Form.Item name="createTimeRange" style={{width: '95%'}}>
                                    <DatePicker.RangePicker placeholder={["创建时间", "创建时间"]}/>
                                </Form.Item>
                            </Col>

                        </Row>
                        <Row style={{width: '100%'}}>


                            <Col span={3} offset={1}>
                                <Form.Item name="username" style={{width: '95%', marginTop: 20}}>
                                    <Input prefix={<UserOutlined/>} placeholder="发放对象"/>
                                </Form.Item>
                            </Col>


                            <Col span={4} offset={1}>
                                <Form.Item name="remark" style={{width: '95%', marginTop: 20}}>
                                    <Input prefix={<MessageOutlined/>} placeholder="备注信息"/>
                                </Form.Item>
                            </Col>

                            <Col span={3} offset={1}>
                                <Form.Item name="keyStatus" style={{marginTop: 20}}>
                                    <Select placeholder="状态" allowClear>
                                        <Option value="NORMAL">正常</Option>
                                        <Option value="DISABLE">禁用</Option>
                                    </Select>
                                </Form.Item>
                            </Col>

                            <Col span={2} offset={1}>
                                <Form.Item style={{marginTop: 20}}>
                                    <Button type="primary" icon={<SearchOutlined/>} htmlType="submit"
                                            style={{backgroundColor: "#13ce66"}}>搜索</Button>
                                </Form.Item>
                            </Col>
                            <Col span={2}>
                                <Form.Item style={{marginTop: 20}}>
                                    <Button type="primary" icon={<ReloadOutlined/>} onClick={this.resetSearchKeys}
                                            style={{backgroundColor: "#ffba00"}}>重置</Button>
                                </Form.Item>
                            </Col>
                        </Row>
                    </Form>

                </Card>

                <Card title="激活码列表" style={{marginTop: 30, marginBottom: 10}}>
                    <Row style={{marginBottom: 10}}>
                        <Col span={2} offset={1}>
                            <Button type="primary" icon={<UserAddOutlined/>}
                                    style={{backgroundColor: "#13ce66"}} onClick={this.createKey}>新增</Button>
                        </Col>
                        <Col span={2}>
                            <Button type="primary" icon={<FormOutlined/>}
                                    style={{backgroundColor: "#1890ff"}} disabled={this.state.selectedRowKey===""} onClick={this.updateKey}>修改</Button>
                        </Col>
                        <Col span={2}>
                            <Button type="primary" icon={<DeleteOutlined/>}
                                    style={{backgroundColor: "#ffa4a4"}}  disabled={this.state.selectedRowKey===""}  onClick={this.disableKey}>禁用</Button>
                        </Col>
                        {/*<Col span={2}>*/}
                        {/*    <Button type="primary" icon={<DownloadOutlined/>}*/}
                        {/*            style={{backgroundColor: "#ffdd80"}}>导出</Button>*/}
                        {/*</Col>*/}
                    </Row>

                    <Table
                        rowSelection={{
                            type: "radio",
                            ...rowSelection
                        }}
                        columns={keyColumns}
                        dataSource={this.state.keys}
                        rowKey={(record) => record.uuid}
                        onChange={this.onTableChange}
                        pagination={pagination}
                        size="small"
                    />
                </Card>


                <CreateVerifyKeyModal onRef={(ref) => {
                    this.setState({createVerifyKeyModal: ref})
                }}/>

                <UpdateVerifyKeyModal onRef={(ref) => {
                    this.setState({updateVerifyKeyModal: ref})
                }} isOwn={this.props.isOwn} keyName={this.state.selectedRowKey}/>

                <DisableVerifyKeyModal onRef={(ref) => {
                    this.setState({disableVerifyKeyModal: ref})
                }} isOwn={this.props.isOwn} keyName={this.state.selectedRowKey}/>
            </div>
        );
    }

}

export default VerifyKeyManagePage